<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="main-content">
      <Split v-model="splitLeft">
        <template #left>
          <o-tree-grid :config="treeConfig"></o-tree-grid>
        </template>
        <template #right>
          <div class="main-right">
            <o-layout
              ref="layout"
              :config="workProcessConfig"
              :parmas="GT_compBoxInfo"
            ></o-layout>
          </div>
        </template>
      </Split>
    </div>
  </div>
</template>

<script lang="ts">
import * as echarts from 'echarts';
import {
  I_cmd,
  N_cAlarmQuery,
  T_cmd,
  T_srv,
  Tsrv,
  ifs,
  treeConfig,
  workProcessConfig,
  getGridOptions,
  vue
} from './config';

type EChartsOption = echarts.EChartsOption;
@T_srv.comp
export default class cAlarmQuery extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  /* 组件名 */
  private name: string = 'cAlarmQuery';

  private funName: string = '';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  /* 遮罩 */
  public isMask: boolean = false;

  private splitLeft: number = 0.15;

  private splitRight: number = 0.5;

  private splitRighTop: number = 0.5;

  private currentCLickCode: N_cAlarmQuery.I_ecBoxDet = null;

  private myChart: echarts.ECharts;

  private treeConfig = treeConfig();

  private workProcessConfig = workProcessConfig();

  private ecBoxDets: N_cAlarmQuery.I_ecBoxDet[] = [];

  // 报警查询实例
  private alarmQueryRef: any;

  // 报警标签集合
  private alarmTags: number[] = [];

  public gridOptions = getGridOptions();

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  destroyed() {
    this.$bus.$off(this.treeConfig.messageConfig.emitActions.search[0].toID);

    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  private init() {
    this.funName = 'cAlarmQuery'; // 当前配置中的功能名
    const funInfo = this.workProcessConfig.config.first.config.funInfo;
    Tsrv.store.commit('SET_FUNINFO', {
      key: 'alarm_query',
      val: funInfo
    });
  }

  /* 设置组件整体遮罩 */
  public setMask(p: boolean) {
    this.isMask = p;
  }

  public getMask(p: boolean): boolean {
    return this.isMask;
  }

  mounted() {
    this.$bus.$on(
      this.treeConfig.messageConfig.emitActions.search[0].toID,
      (msg: any) => {
        this.handleListener(msg);
      }
    );
  }

  private handleListener(msg: any) {
    const custMsg = Tsrv.utils.clone(msg, true);
    const eventID = this.workProcessConfig.config.first.config.messageConfig
      .custDefListener.coordination;
    custMsg.content.ukey = 'alarm_id';
    custMsg.option.autoCompleteInfo.pidField = 'alarm_id';
    custMsg.option.autoCompleteInfo.sourceToID = eventID;
    custMsg.option.autoCompleteInfo.table = 'alarm_query';

    this.GT_command.sendBusEvent(eventID, [custMsg]);
    const filter = {
      alarm_id: { $in: msg.content.val.filter(it => it !== null && it !== -1) }
    };
    this.GT_command.loadFilterList(
      ['alarm_tag_num'],
      'alarm_query',
      filter
    ).then(rows => {
      this.alarmTags = rows.map(row => Number(row.alarm_tag_num));
      this.handleTagRowChange(msg.option.autoCompleteInfo.data);
    });
  }

  // 通过功能名获取该功能事件名
  private getEventName(funName: string): string {
    let eventName = '';
    Tsrv.getFunConf(funName).then(res => {
      if (res.isErr()) {
        console.error(res.errmsg);
      } else {
        const conf = res.getReturnData(funName);
        eventName = conf.messageConfig.custDefListener.coordination;
      }
    });
    return eventName;
  }

  /**
   * @Author: zss
   * @param {any[]} rows 标签
   * @description: 点击树形切换标签
   */
  private handleTagRowChange(row: N_cAlarmQuery.I_treeRowData): void {
    this.ecBoxDets = [];
    const ecDetCodes: N_cAlarmQuery.I_alarmContent[] = [];
    if (!Tsrv.noValue(row.content)) {
      const content = JSON.parse(row.content);
      ecDetCodes.push(...content);
    }
    if (!Tsrv.noValue(row.children)) {
      const childContents = this.getChildContents(row.children);
      !Tsrv.noValue(childContents) && ecDetCodes.push(...childContents);
    }
    if (ecDetCodes.length > 0) {
      this.ecBoxDets = ecDetCodes.map(it => {
        const ecBoxDet: N_cAlarmQuery.I_ecBoxDet = {
          code: it.code,
          title: it.title,
          conversionRate: it.conversion_rate,
          alarmTags: this.alarmTags
        };
        return ecBoxDet;
      });
      // this.ecDetCodeClick(this.ecBoxDets[0], 0);
    } else {
      // 清空表格数据
      this.gridOptions.pagerConfig.total = 0;
      const grid: any = this.$refs.xGrid;
      grid.reloadData([]);
    }
  }

  // 递归获取子节点内容
  private getChildContents(
    rows: N_cAlarmQuery.I_treeRowData[]
  ): N_cAlarmQuery.I_alarmContent[] {
    const childNodes: N_cAlarmQuery.I_alarmContent[] = [];
    rows.forEach(row => {
      if (!Tsrv.noValue(row.children)) {
        childNodes.push(...this.getChildContents(row.children));
      } else {
        !Tsrv.noValue(row.content) &&
          childNodes.push(...JSON.parse(row.content));
      }
    });
    return childNodes;
  }

  public ecDetCodeClick(itm: N_cAlarmQuery.I_ecBoxDet, idx?: number, e?: any) {
    this.currentCLickCode = itm;
    const p = {
      ecCodes: [itm.code],
      beginTime: '2025-01-01 00:00:00',
      endTime: Tsrv.utils.getCurrentTimeStrCN(),
      pageNo: 1,
      pageSize: 30,
      filter: { 'metadata.label': { $in: itm.alarmTags } }
    };
    // this.loadEchartsData(p, itm.conversionRate);
    this.loadTableData(p, itm.conversionRate);
  }

  /**
   * pageChange 翻页
   */
  private pageChange(e: any) {
    if (
      this.gridOptions.pagerConfig.currentPage !== e.currentPage ||
      this.gridOptions.pagerConfig.pageSize !== e.pageSize
    ) {
      this.gridOptions.pagerConfig.currentPage = e.currentPage;
      this.gridOptions.pagerConfig.pageSize = e.pageSize;
      const p: N_cAlarmQuery.I_qryDataReq = {
        ecCodes: [this.currentCLickCode.code],
        beginTime: '2024-01-01 00:00:00',
        endTime: Tsrv.utils.getCurrentTimeStrCN(),
        pageNo: e.currentPage,
        pageSize: e.pageSize
      };
      this.loadTableData(p, this.currentCLickCode.conversionRate);
    }
  }

  public loadTableData(p: N_cAlarmQuery.I_qryDataReq, conversionRate?: number) {
    Tsrv.standardPostReq<N_cAlarmQuery.I_qryDataResp, any>(
      p,
      Tsrv.url.scadaQueryData
    ).then(([resp, err]) => {
      if (err) {
        this.$msg(err);
        return;
      }
      if (!resp.success) {
        this.$msg(resp.msg);
        return;
      }
      const data = JSON.parse(wUnZipStr(resp.data));
      const rowData = data[p.ecCodes[0]]?.d;
      if (!Tsrv.noValue(rowData)) {
        rowData.forEach(it => {
          it.v =
            conversionRate === 1
              ? it.v.toString()
              : (it.v / conversionRate).toString();
        });
      }
      const total = data[p.ecCodes[0]]?.total;
      this.gridOptions.pagerConfig.total = total;
      const grid: any = this.$refs.xGrid;
      grid.reloadData(rowData);
    });
  }
}
</script>
<style lang="scss" scoped>
.main-content {
  height: 100%;
  .main-right {
    height: 100%;
    .main-right-top {
      height: 100%;
      .ec-box-det {
        display: grid;
        // grid-template-columns: repeat(3, 1fr); /* 创建4列，每列宽度相等 */
        gap: 10px; /* 列与列之间的间隙 */
        padding: 10px; /* 容器内边距 */
        grid-template-columns: repeat(auto-fill, minmax(316px, 1fr));
        grid-gap: 10px; /* 网格项之间的间隙 */
        margin-left: 60px;
        margin-top: 2px;
        margin-bottom: 2px;
        margin-right: 2px;
        border: 1px solid #ccc;
        .ec-box-det-item {
          .ec-box-det-item-val {
            margin-left: 3px;
            border-bottom: 1px solid #ccc;
            color: rgb(72, 0, 255);
          }
          .ec-box-det-item-val:hover {
            cursor: help;
          }
          .ec-box-det-item-title {
            margin-right: 3px;
            font-weight: bold;
          }
          .ec-box-det-item-title:hover {
            cursor: pointer;
            background-color: #ccc;
          }
          .val-active {
            color: rgb(72, 0, 255);
          }
        }
      }
      .main-right-top-right {
        height: 100%;
      }
    }
    .main-right-bottom {
      height: 100%;
    }
  }
}
</style>
